<?php
namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller {


    public function index($p='',$i=''){
        $p = I('p');
        $i = I('i');
        if($this->is_sometime_ago()){
            $this->show('the server is busy, please try again later.', 'utf-8');
            return;
        }
        if($i && ($i=intval($i))>0){
        	$entry = M('Entry')->where(['id'=>$i])->field(['id','link_id'])->find();
        	if($entry){
        		M('Entry')->where(['id'=>$i])->setInc('count',1);
                $this->add_record($i);
        		$link = M('Link')->where(['id'=>$entry['link_id']])->find();
        		$this->show_link($link['link']);
        		return;
        	}
        }
        if($p){
        	$entry = M('Entry')->where(['hash'=>$p])->field(['id','link_id'])->find();
        	if($entry){
        		M('Entry')->where(['id'=>$entry['id']])->setInc('count',1);
                $this->add_record($entry['id']);
        		$link = M('Link')->where(['id'=>$entry['link_id']])->find();
        		$this->show_link($link['link']);
        		return;
        	}
        }
        $link = M('Link')->where(['is_default'=>'1'])->find();
    	if($link == false){
    		$link = M('Link')->find();
    	}
    	if($link == false){
    		$this->show('请呼唤程序猿！SOS', 'utf-8');
    		return;
    	}
    	M('Link')->where('id='.$link['id'])->setInc('unknown_count',1);
        $this->add_record(-$link['id']);
    	$this->show_link($link['link']);
    }

    private function show_link($link){
    	//$this->show('看这里：'.$link, 'utf-8');
    	$this->show('<script language="javascript">location.href="'.$link.'";</script>');
    	//$this->redirect($link,1,'页面跳转中...');
    }


    public function login($password=''){
    	if($password == '0K3581H9MPWEF6GUOCB2ZDAI74XRLNYVQSJT'){
    		session('login',true);
    		$this->redirect('/Home/Index/link',[],1,'it will go to the link page.');
    	} else {
    		$this->show('error');
    	}
    }

    public function logout(){
    	session('login',null);
    	$this->redirect('/Home/Index/login',[],1,'it will go to the login page.');
    }


    public function link($id=''){
    	if(!session('?login') || !session('login')){
    		$this->redirect('/Home/Index/login');
    	}
    	if($id){
    		$links = M('Link')->where(['id'=>I('id')])->find();
	    	$this->assign('links', [$links]);
	    	$this->display();
    	} else {
    		$links = M('Link')->select();
	    	$this->assign('links', $links);
	    	$this->display();
    	}
    }

    public function link_detail($id=''){
    	if(!session('?login') || !session('login')){
    		$this->redirect('/Home/Index/login');
    	}
    	$id = I('id');
    	if($id){
    		$link = M('Link')->where(['id'=>$id])->find();
    		$link_entries = M('Entry')->where(['link_id'=>$id])->order('id','asc')->select();
    		$this->assign('link', $link);
    		$this->assign('link_entries', $link_entries);
    		$this->display();
    	} else {
    		$this->show('some parameter(s) is invalid.');
    	}
    }

    public function link_add($name='',$link=''){
    	if(!session('?login') || !session('login')){
    		$this->redirect('/Home/Index/login');
    	}
    	if(strlen($name) > 0 && strlen($link)){
    		$link_model = M('Link');
    		if($link_model->create()){
    			//$link_model['is_default'] = 1;
    			$result = $link_model->add();
    			if ($result) {
    				$data['result'] = 1;
    				$data['id'] = $result;

    				//M('Link')->where('id<>'.$result)->save(['is_default'=>0]);

    				//添加标签
    				$tags = M('Tag')->select();
    				if($tags){
    					foreach ($tags as $tag) {
    						$entry['tag_id'] = $tag['id'];
    						$entry['link_id'] = $result;
    						$entry['count'] = 0;
    						$entry['hash'] = md5($tag['tag'].$this->get_rand_char(20));
    						M('Entry')->data($entry)->add();
    						unset($entry);
    					}
    				}
    				$this->redirect('/Home/Index/link',[],1,'the link has been added.');
    				return;
    			} else {
    				$data['result'] = 0;
    				$data['msg'] = $result;
    				$this->ajaxReturn($data,'JSON');
    			}
    		} else {
				$data['result'] = 0;
				$data['msg'] = 'creating failed';
				$this->ajaxReturn($data,'JSON');
    		}
    	} else {
			$data['result'] = 0;
			$data['msg'] = 'some parameter(s) is invalid.';
			$this->ajaxReturn($data,'JSON');
    	}
    }

    public function link_del($id=''){
    	if(!session('?login') || !session('login')){
    		$this->redirect('/Home/Index/login');
    	}
    	$id = I('id');
    	if($id){
    		M('Link')->delete($id);
    		$this->redirect('/Home/Index/link',[],1,'the link has been deleted.');
    	} else {
    		$data['result'] = 0;
			$data['msg'] = 'some parameter(s) is invalid.';
			$this->ajaxReturn($data,'JSON');
    	}
    }

    private function getmillisecond() { 
    	list($s1, $s2) = explode(' ', microtime()); 
    	return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); 
	}

    public function tag(){
    	if(!session('?login') || !session('login')){
    		$this->redirect('/Home/Index/login');
    	}
    	$tags = M('Tag')->select();
    	$this->assign('tags',$tags);
	    $this->display();
    }

    public function tag_auto_add(){
    	if(!session('?login') || !session('login')){
    		$this->redirect('/Home/Index/login');
    	}
    	for($i = 0; $i < 10; $i ++){
    		$data['name'] = $data['tag'] = $this->get_rand_char(20);
    		M('Tag')->data($data)->add();
    		unset($data);
    	}
    	$this->redirect('/Home/Index/tag',[],1,'10 tags have been added.');
    }

    public function add_record($entry_id=''){
        $ip = $this->get_ip();
        $data['ip'] = $ip;
        $data['address'] = substr($this->get_ip_address($ip),0,255);
        $data['agent'] = substr($_SERVER['HTTP_USER_AGENT'],0,1023);
        $data['os'] = $this->get_os();
        $data['browser'] = $this->get_browser();
        $data['entry_id'] = $entry_id;
        $data['download_time'] = date('Y-m-d H:i:s',time());
        M('Record')->data($data)->add();
    }

    public function is_sometime_ago(){
        $ip = $this->get_ip();
        $rec = M('Record')->where('ip=\''.$ip.'\' and download_time>\''.date('Y-m-d H:i:s',time()-30).'\'')->find();
        if($rec){
            return true;
        } else {
            return false;
        }
    }



    private function get_rand_char($length){
		$str = null;
		$strPol = "0123456789abcdefghijklmnopqrstuvwxyz";
		$max = strlen($strPol) - 1;

		for($i = 0;$i < $length; $i++){
			$str .= $strPol[rand(0, $max)];
		}
		return $str;
    }

    private function show_info(){
        $ip = $this->get_ip();
        echo 'IP:'.$ip;
        echo '<br />Addr:'.$this->get_ip_address($ip);
        echo '<br />browser:'.$this->get_browser();
        echo '<br />os:'.$this->get_os();
        echo '<br />agent:'.$_SERVER['HTTP_USER_AGENT'];
    }



    private function get_ip(){
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){//获取代理ip
            $ips = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
        }
        if($ip){
            $ips = array_unshift($ips,$ip);
        }
   
        $count = count($ips);
        for($i = 0; $i < $count; $i ++){
            if(!preg_match("/^(10|172\.16|192\.168)\./i",$ips[$i])){//排除局域网ip
                $ip = $ips[$i];
                break;
            }
        }
        $tip = empty($_SERVER['REMOTE_ADDR']) ? $ip : $_SERVER['REMOTE_ADDR'];
        return $tip;
    }

    ////根据ip获得访客所在地地名
    private function get_ip_address($ip=''){
        if(empty($ip)){
            return 'unknown';
        }
        return iconv("gbk","utf-8",file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=".$ip));
        /*
        if($ipadd){
            $charset = iconv("gbk","utf-8",$ipadd);
            preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$charset,$ipadds);
            return $ipadds;   //返回一个二维数组
        } else {
            return [["unknown"]];
        }//*/
    }

    private function get_browser(){
        if(!empty($_SERVER['HTTP_USER_AGENT'])){
            $br = $_SERVER['HTTP_USER_AGENT'];
            if(preg_match('/MSIE/i',$br)) {
                $br = 'MSIE';
            } elseif (preg_match('/Firefox/i',$br)) {
                $br = 'Firefox';
            } elseif (preg_match('/Chrome/i',$br)) {
                $br = 'Chrome';
            } elseif (preg_match('/Safari/i',$br)) {
                $br = 'Safari';
            } elseif (preg_match('/Opera/i',$br)) {
                $br = 'Opera';
            } else {
                $br = 'Other';
            }
            return $br;
        } else {
            return "unknown";
        }
    }
  
    ////获得访客浏览器语言
    private function get_lang(){
        if(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
            $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
            $lang = substr($lang,0,5);
            if(preg_match("/zh-cn/i",$lang)){
                $lang = "简体中文";
            } elseif(preg_match("/zh/i",$lang)){
                $lang = "繁体中文";
            } else {
                $lang = "English";
            }
            return $lang;
        } else {
            return "unknown";
        }
    }
  
    ////获取访客操作系统
    private function get_os(){
        if(!empty($_SERVER['HTTP_USER_AGENT'])){
            $os = $_SERVER['HTTP_USER_AGENT'];
            if (preg_match('/win/i',$os)) {
                $os = 'Windows';
            } elseif (preg_match('/mac/i',$os)) {
                $os = 'MAC';
            } elseif (preg_match('/linux/i',$os)) {
                $os = 'Linux';
            } elseif (preg_match('/unix/i',$os)) {
                $os = 'Unix';
            } elseif (preg_match('/bsd/i',$os)) {
                $os = 'BSD';
            } else {
                $os = 'Other';
            }
            return $os;  
        } else {
            return "unknown";
        }
    }
}